package com.example.forwardmessages

import android.content.Context
import android.util.Log
import fi.iki.elonen.NanoHTTPD
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import javax.mail.Session
import javax.mail.Transport
import com.example.forwardmessages.NotificationHelper
import com.example.forwardmessages.AppConfig
import com.example.forwardmessages.SmsMessage

interface SmsRefreshCallback {
    fun onRefreshSmsMessages()
}

class WebServer(private val context: Context, private val port: Int) : NanoHTTPD(port) {
    private lateinit var notificationHelper: NotificationHelper
    // 存储短信列表的变量
    private var smsMessages: List<SmsMessage> = emptyList()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    // HTTP请求计数器，用于每5次请求刷新消息
    private var requestCounter = 0
    // 标志变量，用于标识是否需要显示刷新alert提示
    private var shouldShowRefreshAlert = false
    // 短信刷新回调接口
    private var smsRefreshCallback: SmsRefreshCallback? = null
    
    fun setSmsRefreshCallback(callback: SmsRefreshCallback?) {
        this.smsRefreshCallback = callback
    }

    init {
        // Initialize notification helper
        notificationHelper = NotificationHelper(context)
        
        // 尝试启动服务器
        try {
            start(NanoHTTPD.SOCKET_READ_TIMEOUT, false)
            println("Web server started on port $port")
        } catch (e: IOException) {
            e.printStackTrace()
            println("Failed to start web server: ${e.message}")
            notificationHelper.showErrorNotification("WebServer", "启动失败: 端口被占用或无法绑定", e)
        } catch (e: SecurityException) {
            e.printStackTrace()
            println("Security exception when starting web server: ${e.message}")
            notificationHelper.showErrorNotification("WebServer", "启动失败: 安全权限错误", e)
        } catch (e: Exception) {
            e.printStackTrace()
            println("Unexpected exception when starting web server: ${e.message}")
            notificationHelper.showErrorNotification("WebServer", "启动失败: ${e.message}", e)
        }
    }

    /**
     * 设置要显示的短信列表
     */
    fun setSmsMessages(messages: List<SmsMessage>) {
        this.smsMessages = messages
        // 添加日志记录，确认短信数据已更新
        println("WebServer: 已更新短信列表，当前短信数量: \${smsMessages.size}")
    }

    /**
     * 停止Web服务器
     */
    fun stopServer() {
        stop()
        println("Web server stopped")
    }

    /**
     * 处理HTTP请求
     */
    override fun serve(session: IHTTPSession): Response {
        val uri = session.uri
        val method = session.method

        // 增加请求计数
        requestCounter++
        println("WebServer: 当前请求计数: $requestCounter")
        
        // 每5次请求刷新一次消息
        if (requestCounter % 3 == 0) {
            println("WebServer: 请求达到3次，触发消息刷新")
            // 设置标志为true，表示需要显示刷新alert提示
            shouldShowRefreshAlert = true
            // 调用回调通知FirstFragment重新加载短信数据
            smsRefreshCallback?.onRefreshSmsMessages()
            // 在Android应用中显示通知
            notificationHelper.showInfoNotification(
                "消息刷新",
                "已完成第${requestCounter}次HTTP请求，系统自动刷新了消息列表"
            )
        }

        // 处理不同的HTTP请求方法和URI
        return when {
            method == Method.GET && uri == "/" -> {
                // 返回短信列表的HTML页面
                createSmsListHtmlResponse()
            }
            method == Method.GET && uri == "/api/sms" -> {
                // 返回JSON格式的短信数据
                createSmsJsonResponse()
            }
            method == Method.POST && uri == "/api/send-email" -> {
                // 处理发送邮件请求
                handleSendEmailRequest()
            }
            else -> {
                // 返回404错误
                newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "Page not found")
            }
        }
    }

    /**
     * 处理发送邮件请求
     */
    private fun handleSendEmailRequest(): Response {
        try {
            // 获取应用配置
            val appConfig = AppConfig(context)
            val smtpServer = appConfig.smtpServer
            val smtpPort = appConfig.smtpPort
            val emailUser = appConfig.emailUser
            val emailPassword = appConfig.emailPassword
            val recipientEmail = appConfig.recipientEmail

            // 检查必要的邮箱配置
            if (!appConfig.isEmailConfigComplete()) {
                Log.e("WebServer", "邮箱配置不完整")
                notificationHelper.showErrorNotification("WebServer", "邮箱配置不完整，请在应用中配置SMTP信息")
                return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json", 
                    "{\"success\": false, \"message\": \"邮箱配置不完整\"}")
            }

            // 获取最近的一条短信作为示例数据
            val recentSms = smsMessages.firstOrNull()
            val sender = recentSms?.address ?: "系统"
            val content = recentSms?.body ?: "这是一封测试邮件，由Web服务器触发发送。"
            val time = recentSms?.let { dateFormat.format(Date(it.date)) } ?: dateFormat.format(Date())

            // 构建邮件内容
            val emailSubject = "[手动触发] 来自Web界面的消息"
            val emailBody = buildEmailBody(sender, content, time)

            // 发送邮件到默认邮箱
            sendEmail(smtpServer, smtpPort, emailUser, emailPassword, recipientEmail, emailSubject, emailBody)

            // 显示成功通知
            notificationHelper.showInfoNotification("邮件发送成功", "已成功发送邮件到 $recipientEmail")
            
            return newFixedLengthResponse(Response.Status.OK, "application/json", 
                "{\"success\": true, \"message\": \"邮件发送成功\"}")

        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("WebServer", "邮件发送失败: ${e.message}")
            notificationHelper.showErrorNotification("WebServer", "邮件发送失败: ${e.message ?: "未知错误"}", e)
            
            return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, "application/json", 
                "{\"success\": false, \"message\": \"${e.message?.replace("\"", "\\\"") ?: "未知错误"}\"}")
        }
    }

    /**
     * 构建邮件内容
     */
    private fun buildEmailBody(sender: String, content: String, time: String): String {
        val body = StringBuilder()
        body.append("发件人: $sender\n")
        body.append("时间: $time\n")
        body.append("触发方式: Web界面手动触发\n")
        body.append("\n\n消息内容:\n")
        body.append(content)
        return body.toString()
    }

    /**
     * 发送邮件
     */
    private fun sendEmail(
        smtpServer: String,
        smtpPort: Int,
        emailUser: String,
        emailPassword: String,
        recipientEmail: String,
        subject: String,
        body: String
    ) {
        // 设置邮件属性
        val props = Properties()
        props["mail.smtp.host"] = smtpServer
        props["mail.smtp.port"] = smtpPort.toString()
        props["mail.smtp.auth"] = "true"
        props["mail.smtp.starttls.enable"] = "true"

        // 创建会话
        val session = Session.getInstance(props, object : javax.mail.Authenticator() {
            override fun getPasswordAuthentication(): javax.mail.PasswordAuthentication {
                return javax.mail.PasswordAuthentication(emailUser, emailPassword)
            }
        })

        // 创建并发送邮件
        val message = javax.mail.internet.MimeMessage(session)
        message.setFrom(javax.mail.internet.InternetAddress(emailUser))
        message.addRecipient(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress(recipientEmail))
        message.subject = subject
        message.setText(body)

        javax.mail.Transport.send(message)
    }

    /**
     * 创建包含短信列表的HTML响应
     */
    private fun createSmsListHtmlResponse(): Response {
        val html = StringBuilder()
        html.append("""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>短信列表</title>
                <style>
                body {
                    font-family: Arial, sans-serif;
                    margin: 0;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                h1 {
                    color: #333;
                    text-align: center;
                }
                .sms-container {
                    max-width: 800px;
                    margin: 0 auto;
                }
                .sms-item {
                    background-color: #fff;
                    border-radius: 8px;
                    padding: 15px;
                    margin-bottom: 10px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                }
                .sms-sender {
                    font-weight: bold;
                    color: #0066cc;
                    margin-bottom: 5px;
                }
                .sms-time {
                    font-size: 12px;
                    color: #666;
                    margin-bottom: 8px;
                }
                .sms-content {
                    color: #333;
                    white-space: pre-wrap;
                    word-break: break-word;
                }
                .empty-message {
                    text-align: center;
                    color: #666;
                    padding: 40px;
                    background-color: #fff;
                    border-radius: 8px;
                    margin-top: 20px;
                }
                @media (max-width: 600px) {
                    .sms-container {
                        padding: 0;
                    }
                    .sms-item {
                        border-radius: 0;
                        margin-bottom: 5px;
                    }
                }
                .sms-meta {
                    text-align: center;
                    color: #666;
                    margin-bottom: 15px;
                    font-size: 14px;
                }
                .hint {
                    text-align: center;
                    color: #999;
                    margin-top: 10px;
                    font-size: 12px;
                }
                .button-container {
                    text-align: center;
                    margin: 20px 0;
                }
                .send-button {
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    font-size: 16px;
                    border-radius: 4px;
                    cursor: pointer;
                    transition: background-color 0.3s;
                }
                .send-button:hover {
                    background-color: #45a049;
                }
                .send-button:disabled {
                    background-color: #cccccc;
                    cursor: not-allowed;
                }
                .loading {
                    display: none;
                    text-align: center;
                    color: #666;
                    margin-top: 10px;
                }
                .response-message {
                    text-align: center;
                    margin-top: 15px;
                    padding: 10px;
                    border-radius: 4px;
                    display: none;
                }
                .success-message {
                    background-color: #d4edda;
                    color: #155724;
                    border: 1px solid #c3e6cb;
                }
                .error-message {
                    background-color: #f8d7da;
                    color: #721c24;
                    border: 1px solid #f5c6cb;
                }
            </style>
        </head>
            <body>
                <h1>短信列表</h1>
                <div class="sms-container">
                    <div class="button-container">
                        <button id="sendEmailBtn" class="send-button">发送邮件到默认邮箱</button>
                    </div>
                    <div id="loading" class="loading">正在发送邮件，请稍候...</div>
                    <div id="responseMessage" class="response-message"></div>
        """)

        // 添加短信列表
        html.append("<div class='sms-meta'>当前短信数量: \${smsMessages.size}</div>")
        if (smsMessages.isNotEmpty()) {
            for (message in smsMessages) {
                val formattedTime = dateFormat.format(Date(message.date))
                html.append("""
                <div class="sms-item">
                    <div class="sms-sender">\${escapeHtml(message.address)}</div>
                    <div class="sms-time">\${formattedTime}</div>
                    <div class="sms-content">\${escapeHtml(message.body)}</div>
                </div>
                """)
            }
        } else {
            html.append("<div class='empty-message'>暂无短信数据</div>")
            html.append("<div class='hint'>请确保已授予应用读取短信权限并刷新页面</div>")
        }

        // 添加JavaScript逻辑
        html.append("""
                </div>
                <script>
                    // 发送邮件按钮点击事件
                    document.getElementById('sendEmailBtn').addEventListener('click', function() {
                        const btn = this;
                        const loading = document.getElementById('loading');
                        const responseMessage = document.getElementById('responseMessage');
                         
                        // 禁用按钮，显示加载状态
                        btn.disabled = true;
                        loading.style.display = 'block';
                        responseMessage.style.display = 'none';
                         
                        // 发送POST请求到/api/send-email
                        fetch('/api/send-email', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            // 更新UI显示结果
                            loading.style.display = 'none';
                            btn.disabled = false;
                            
                            responseMessage.textContent = data.message;
                            responseMessage.className = 'response-message ' + (data.success ? 'success-message' : 'error-message');
                            responseMessage.style.display = 'block';
                             
                            // 3秒后隐藏消息
                            setTimeout(() => {
                                responseMessage.style.display = 'none';
                            }, 3000);
                        })
                        .catch(error => {
                            // 处理错误情况
                            loading.style.display = 'none';
                            btn.disabled = false;
                            
                            responseMessage.textContent = '发送请求失败: ' + (error.message || '未知错误');
                            responseMessage.className = 'response-message error-message';
                            responseMessage.style.display = 'block';
                        });
                    });

                    // 自动刷新页面（可选）
                    // setTimeout(function() {
                    //     window.location.reload();
                    // }, 30000); // 每30秒刷新一次
                </script>
            </body>
            </html>
        """)

        return newFixedLengthResponse(Response.Status.OK, "text/html; charset=UTF-8", html.toString())
    }

    /**
     * 创建JSON格式的短信响应
     */
    private fun createSmsJsonResponse(): Response {
        val jsonBuilder = StringBuilder()
        jsonBuilder.append("{")
        jsonBuilder.append("\"messages\":[")

        if (smsMessages.isNotEmpty()) {
            for (i in smsMessages.indices) {
                val message = smsMessages[i]
                val formattedTime = dateFormat.format(Date(message.date))
                
                jsonBuilder.append("{")
                jsonBuilder.append("\"id\":\"${escapeJson(message.id)}\",")
                jsonBuilder.append("\"address\":\"${escapeJson(message.address)}\",")
                jsonBuilder.append("\"body\":\"${escapeJson(message.body)}\",")
                jsonBuilder.append("\"date\":${message.date},")
                jsonBuilder.append("\"formattedDate\":\"${escapeJson(formattedTime)}\",")
                jsonBuilder.append("\"read\":${message.read}")
                jsonBuilder.append("}")

                if (i < smsMessages.size - 1) {
                    jsonBuilder.append(",")
                }
            }
        }

        jsonBuilder.append("]")
        jsonBuilder.append("}")

        return newFixedLengthResponse(Response.Status.OK, "application/json; charset=UTF-8", jsonBuilder.toString())
    }

    /**
     * 转义HTML特殊字符
     */
    private fun escapeHtml(text: String): String {
        return text
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\"", "&quot;")
            .replace("'", "&#039;")
    }

    /**
     * 转义JSON特殊字符
     */
    private fun escapeJson(text: String): String {
        return text
            .replace("\\", "\\\\")
            .replace("\"", "\\\"")
            .replace("\n", "\\n")
            .replace("\r", "\\r")
            .replace("\t", "\\t")
    }
}